#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<queue>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution {
    struct cmp
    {
        bool operator()(const pair<string, int>& a1, const pair<string, int>& a2)
        {
            if (a1.second == a2.second)
            {
                return a1.first < a2.first;
            }
            return a1.second > a2.second;
        }
    };
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> as;
        priority_queue<pair<string, int>, vector<pair<string, int>>, cmp> aq;
        vector<string> ret(k);
        for (auto& e : words)
        {
            as[e]++;
        }
        for (auto& s : as)
        {
            aq.push(s);
            if (aq.size() > k)
            {
                aq.pop();
            }
        }
        for (int i = k - 1; i >= 0; i--)
        {
            ret[i] = aq.top().first;
            aq.pop();
        }
        return ret;
    }
};